<template>
  <view class="w-[750rpx] bg-gray-50 min-h-screen pgs">
    <!-- Header -->
    <PageHeader title="编辑签到任务" />

    <!-- Content -->
    <view class="p-[40rpx]">
      <nut-form ref="formRef" :model-value="formData">
        <!-- 任务标题 -->
        <view class="mb-[40rpx] bg-white rounded-[16rpx] p-[30rpx] shadow-sm">
          <view class="text-[32rpx] font-semibold mb-[16rpx] text-gray-800">
            任务标题 <text class="text-red-500">*</text>
          </view>
          <nut-input
            v-model="formData.title"
            placeholder="例如：每日健康打卡"
            class="w-full"
          />
        </view>

        <!-- 任务描述 -->
        <view class="mb-[40rpx] bg-white rounded-[16rpx] p-[30rpx] shadow-sm">
          <view class="text-[32rpx] font-semibold mb-[16rpx] text-gray-800"
            >任务描述</view
          >
          <nut-textarea
            v-model="formData.description"
            placeholder="描述签到任务的具体内容和要求..."
            rows="4"
          />
          <view class="text-[26rpx] text-gray-500 mt-[10rpx]"
            >建议详细说明签到规则和要求</view
          >
        </view>

        <!-- 时间设置 -->
        <view class="bg-white rounded-[16rpx] p-[30rpx] shadow-sm mb-[40rpx]">
          <view
            class="text-[36rpx] font-semibold mb-[30rpx] pb-[16rpx] border-b border-gray-200 text-blue-500 flex items-center"
          >
            时间设置
          </view>

          <!-- 开始和结束日期 -->
          <view class="flex gap-[30rpx] mb-[40rpx]">
            <view class="flex-1">
              <view class="text-[32rpx] font-semibold mb-[16rpx] text-gray-800">
                开始日期 <text class="text-red-500">*</text>
              </view>
              <view
                @click="showStartDatePicker = true"
                class="p-[28rpx] border border-gray-300 rounded-[16rpx] text-[30rpx] bg-[#f0f0f0] active:bg-gray-50 transition-colors cursor-pointer"
              >
                <text
                  :class="
                    formData.startDate ? 'text-gray-800' : 'text-gray-400'
                  "
                >
                  {{ formData.startDate || "请选择开始日期" }}
                </text>
              </view>
            </view>
            <view class="flex-1">
              <view class="text-[32rpx] font-semibold mb-[16rpx] text-gray-800"
                >结束日期</view
              >
              <view
                @click="showEndDatePicker = true"
                class="p-[28rpx] border border-gray-300 rounded-[16rpx] text-[30rpx] bg-[#f0f0f0] active:bg-gray-50 transition-colors cursor-pointer"
              >
                <text
                  :class="formData.endDate ? 'text-gray-800' : 'text-gray-400'"
                >
                  {{ formData.endDate || "请选择结束日期" }}
                </text>
              </view>
              <view class="text-[26rpx] text-gray-500 mt-[10rpx]"
                >留空表示长期有效</view
              >
            </view>
          </view>

          <!-- 每日签到时间段 -->
          <view class="mb-[40rpx]">
            <view class="text-[32rpx] font-semibold mb-[16rpx] text-gray-800">
              每日签到时间段 <text class="text-red-500">*</text>
            </view>
            <view class="flex gap-[30rpx]">
              <view
                @click="showStartTimePicker = true"
                class="flex-1 p-[28rpx] border border-gray-300 rounded-[16rpx] text-[30rpx] bg-[#f0f0f0] active:bg-gray-50 transition-colors cursor-pointer text-center"
              >
                <text
                  :class="
                    formData.startTime ? 'text-gray-800' : 'text-gray-400'
                  "
                >
                  {{ formData.startTime || "开始时间" }}
                </text>
              </view>
              <view
                class="flex items-center justify-center text-gray-400 text-[24rpx]"
                >至</view
              >
              <view
                @click="showEndTimePicker = true"
                class="flex-1 p-[28rpx] border border-gray-300 rounded-[16rpx] text-[30rpx] bg-[#f0f0f0] active:bg-gray-50 transition-colors cursor-pointer text-center"
              >
                <text
                  :class="formData.endTime ? 'text-gray-800' : 'text-gray-400'"
                >
                  {{ formData.endTime || "结束时间" }}
                </text>
              </view>
            </view>
            <view class="text-[26rpx] text-gray-500 mt-[10rpx]"
              >设置每天允许签到的时间范围</view
            >
          </view>
        </view>

        <!-- 签到地址设置 -->
        <view class="bg-white rounded-[16rpx] p-[30rpx] shadow-sm mb-[40rpx]">
          <view
            class="text-[36rpx] font-semibold mb-[30rpx] pb-[16rpx] border-b border-gray-200 text-blue-500 flex items-center"
          >
            签到地址设置
          </view>

          <view class="mb-[40rpx]">
            <view class="text-[32rpx] font-semibold mb-[16rpx] text-gray-800">
              签到位置 <text class="text-red-500">*</text>
            </view>
            <nut-input
              v-model="formData.address.detail"
              placeholder="输入或选择签到地点"
              class="w-full !my-[10rpx]"
            />
            <nut-button
              type="primary"
              size="small"
              @click="selectLocation"
              class="w-full flex-center !my-[10rpx]"
              style="display: flex; align-items: center"
            >
              <template #icon>
                <IconFont
                  name="location"
                  size="14"
                  class="mr-[10rpx]"
                ></IconFont>
              </template>
              <text>选择位置</text>
            </nut-button>

            <!-- 地址详情 -->
            <view
              class="bg-white border border-gray-200 rounded-[16rpx] mt-[30rpx] shadow-sm"
            >
              <!-- <view class="mb-[30rpx]">
                <view
                  class="text-[32rpx] font-semibold mb-[16rpx] text-gray-800"
                  >详细地址</view
                >
                <nut-input
                  v-model="formData.address.detail"
                  placeholder="请输入详细地址"
                  class="w-full"
                />
              </view> -->

              <view class="mb-[30rpx]">
                <view
                  class="text-[32rpx] font-semibold mb-[16rpx] text-gray-800"
                  >位置坐标</view
                >
                <view class="flex gap-[30rpx]">
                  <nut-input
                    v-model="formData.address.lat"
                    placeholder="纬度"
                    class="flex-1"
                  />
                  <nut-input
                    v-model="formData.address.lng"
                    placeholder="经度"
                    class="flex-1"
                  />
                </view>
                <view class="text-[26rpx] text-gray-500 mt-[10rpx]"
                  >可手动输入或通过选择位置自动填入</view
                >
              </view>

              <view class="mb-[30rpx]">
                <view
                  class="text-[32rpx] font-semibold mb-[16rpx] text-gray-800"
                  >位置预览</view
                >
                <div
                  class="h-[300rpx] bg-gradient-to-br from-blue-50 to-gray-100 rounded-[12rpx] flex items-center justify-center text-gray-500 border-2 border-dashed border-gray-300"
                  id="map-container"
                >
                  <view class="text-center" v-if="!formData.address.lng">
                    <IconFont
                      name="location"
                      size="24"
                      class="mb-[10rpx] text-blue-400"
                    ></IconFont>
                    <view class="text-[28rpx]">位置地图预览</view>
                    <view class="text-[24rpx] mt-[5rpx]"
                      >选择位置后显示地图</view
                    >
                  </view>
                </div>
              </view>

              <view>
                <view
                  class="text-[32rpx] font-semibold mb-[16rpx] text-gray-800"
                  >签到范围（米）</view
                >
                <nut-input
                  v-model="formData.address.range"
                  type="number"
                  placeholder="100"
                  class="w-full"
                />
                <view class="text-[26rpx] text-gray-500 mt-[10rpx]"
                  >设置允许签到的最大距离范围，建议5-10米</view
                >
              </view>
            </view>
          </view>
        </view>

        <!-- 任务金额设置 -->
        <view class="bg-white rounded-[16rpx] p-[30rpx] shadow-sm mb-[40rpx]">
          <view class="text-[36rpx] font-semibold mb-[30rpx] pb-[16rpx] border-b border-gray-200 text-blue-500 flex items-center">
            任务设置
          </view>

          <view class="mb-[40rpx]">
            <view class="text-[32rpx] font-semibold mb-[16rpx] text-gray-800"> 签到人数 <text class="text-red-500">*</text> </view>
            <view class="flex gap-[20rpx] items-center">
              <nut-input v-model="formData.number" type="number" placeholder="请输入签到人数" class="flex-1" />
            </view>
          </view>


          <view class="mb-[40rpx]">
            <view class="text-[32rpx] font-semibold mb-[16rpx] text-gray-800"> 任务金额 <text class="text-red-500">*</text> </view>
            <view class="flex gap-[20rpx] items-center">
              <nut-input v-model="formData.amount" type="number" placeholder="请输入任务金额" class="flex-1" />
              <view class="w-[80rpx] p-[20rpx] border border-blue-200 rounded-[16rpx] text-[30rpx] text-center bg-blue-50 text-blue-600 font-semibold"> 元 </view>
            </view>
            <view class="text-[26rpx] text-gray-500 mt-[10rpx]">设置完成此签到任务可获得的金额奖励</view>
          </view>

        </view>

        <!-- 提交按钮 -->
        <view class="mt-[60rpx] pb-[40rpx]">
          <nut-button
            type="primary"
            size="large"
            @click="submitForm"
            class="w-full h-[100rpx] text-[36rpx] font-semibold rounded-[20rpx] shadow-lg"
          >
            保存修改
          </nut-button>
        </view>
      </nut-form>
    </view>

    <!-- 日期选择器 -->
    <nut-calendar
      v-model:visible="showStartDatePicker"
      v-model="startDateValue"
      title="选择开始日期"
      @choose="onStartDateConfirm"
      @close="showStartDatePicker = false"
    />

    <nut-calendar
      v-model:visible="showEndDatePicker"
      v-model="endDateValue"
      title="选择结束日期"
      @choose="onEndDateConfirm"
      @close="showEndDatePicker = false"
    />

    <!-- 时间选择器 -->
    <nut-popup v-model:visible="showStartTimePicker" position="bottom" round>
      <nut-picker
        v-model:visible="showStartTimePicker"
        v-model="startTimeValue"
        :columns="timeColumns"
        title="选择开始时间"
        @confirm="onStartTimeConfirm"
      />
    </nut-popup>

    <nut-popup v-model:visible="showEndTimePicker" position="bottom" round>
      <nut-picker
        v-model="endTimeValue"
        :columns="timeColumns"
        title="选择结束时间"
        @confirm="onEndTimeConfirm"
      />
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import Taro from "@tarojs/taro";
import { IconFont } from "@nutui/icons-vue-taro";
import PageHeader from "@/components/PageHeader.vue";
import { post } from "../../utils/request";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";

const userStore = useUserStore();
const { locationObj } = storeToRefs(userStore);
const { getAddressInfo } = storeToRefs(userStore);

// 获取路由参数
const taskId = ref('');
const taskType = ref('');

// 表单数据
const formData = reactive({
  title: "",
  description: "",
  startDate: "",
  endDate: "",
  startTime: "",
  endTime: "",
  address: {
    name: "",
    detail: "",
    lat: "",
    lng: "",
    range: "100",
  },
  amount: "",
});

// 选择器显示状态
const showStartDatePicker = ref(false);
const showEndDatePicker = ref(false);
const showStartTimePicker = ref(false);
const showEndTimePicker = ref(false);

// 选择器值
const startDateValue = ref<string>("");
const endDateValue = ref<string>("");
const startTimeValue = ref<string[]>(["09", "00"]);
const endTimeValue = ref<string[]>(["18", "00"]);

// 时间选择器列数据
const timeColumns = ref([
  // 小时列
  Array.from({ length: 24 }, (_, i) => ({
    text: String(i).padStart(2, "0"),
    value: String(i).padStart(2, "0"),
  })),
  // 分钟列
  Array.from({ length: 60 }, (_, i) => ({
    text: String(i).padStart(2, "0"),
    value: String(i).padStart(2, "0"),
  })),
]);

// 获取任务详情
const getTaskDetail = async () => {
  try {
    const res = await post('/check/detail', { id: taskId.value });
    if (res.code === 0 && res.data) {
      const taskData = res.data.columns;
      formData.id = taskData.id;
      // 填充表单数据
      formData.title = taskData.title || '';
      formData.description = taskData.describe_str || '';
      formData.startDate = taskData.start_date || '';
      formData.endDate = taskData.end_date || '';
      formData.startTime = taskData.check_time?.split(' ').pop() || '';
      formData.endTime = taskData.deadline || '';
      formData.amount = taskData.single_amount || '';
      
      // 地址信息
      formData.address.name = taskData.full_address || '';
      formData.address.detail = taskData.full_address || '';
      formData.address.lat = taskData.latitude || '';
      formData.address.lng = taskData.longitude || '';
      formData.address.range = taskData.check_range || '100';
      formData.number = taskData.number || '';
      
      // 设置选择器值
      startDateValue.value = formData.startDate;
      endDateValue.value = formData.endDate;
      
      // 设置时间选择器值
      if (formData.startTime) {
        const [startHour, startMinute] = formData.startTime.split(':');
        startTimeValue.value = [startHour, startMinute];
      }
      if (formData.endTime) {
        const [endHour, endMinute] = formData.endTime.split(':');
        endTimeValue.value = [endHour, endMinute];
      }
      
      // 初始化地图
      if (formData.address.lat && formData.address.lng) {
        initMap(parseFloat(formData.address.lat), parseFloat(formData.address.lng));
      }
    }
  } catch (error) {
    console.error('获取任务详情失败:', error);
    Taro.showToast({
      title: '获取任务详情失败',
      icon: 'none'
    });
  }
};

// 日期确认
const onStartDateConfirm = (date: string) => {
  console.log("date", date);
  formData.startDate = date[3];
  showStartDatePicker.value = false;
};

const onEndDateConfirm = (date: string) => {
  console.log("date", date);
  formData.endDate = date[3];
  showEndDatePicker.value = false;
};

// 时间确认
const onStartTimeConfirm = () => {
  formData.startTime = `${startTimeValue.value[0]}:${startTimeValue.value[1]}`;
  showStartTimePicker.value = false;
};

const onEndTimeConfirm = () => {
  formData.endTime = `${endTimeValue.value[0]}:${endTimeValue.value[1]}`;
  showEndTimePicker.value = false;
};

// 创建 MultiMarker 图层（修复图标设置）
let multiMarker = null;
let map = null;
let markers = [];

// 初始化地图
function initMap(lat: any, lng: any) {
  // 确保地图容器存在
  const mapContainer = document.getElementById("map-container");
  if (!mapContainer) {
    console.error("地图容器不存在，请检查DOM元素");
    return;
  }

  map = new TMap.Map("map-container", {
    center: new TMap.LatLng(lat, lng),
    zoom: 13,
    pitch: 50,
    styleId: "style1",
  });

  // 创建 MultiMarker 图层（修复图标设置）
  multiMarker = new TMap.MultiMarker({
    map: map,
    styles: {
      default: new TMap.MarkerStyle({
        width: 30, // 图标宽度
        height: 30, // 图标高度
        anchor: { x: 0.5, y: 1 }, // 锚点位置（图标底部中心）
        src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/marker.png", // 图标URL
        fallbackSrc:
          "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/marker.png",
      }),
    },
    geometries: [],
  });

  // 验证图标URL是否有效
  const testImg = new Image();
  testImg.src = "https://www.h5.nl9555.com/share.png";
  testImg.onerror = () => console.error("标记图标URL无效或无法访问");

  map.on("click", handleMapClick);
}

// 处理地图点击事件（优化版）
async function handleMapClick(e: any) {
  clearMarkers(); // 清除已有标记
  const position = e.latLng;

  try {
    const lat = position.getLat();
    const lng = position.getLng();

    // 创建新标记数据
    const newMarker = {
      id: `marker_${Date.now()}`, // 唯一ID
      styleId: "default", // 使用预定义的样式
      position: new TMap.LatLng(lat, lng),
    };

    // 添加到标记数组
    markers.push(newMarker);

    // 更新图层显示新标记
    multiMarker.setGeometries(markers);
    console.log(multiMarker.getGeometries());

    // 获取地址信息
    const addressInfo = await userStore.getAddressInfo(lat, lng);
    // 更新地址信息
    formData.address.name = addressInfo.address;
    formData.address.detail =
    addressInfo.formatted_addresses.standard_address;
    formData.address.lat = addressInfo.location.lat;
    formData.address.lng = addressInfo.location.lng;

    // 更新地图中心
    map.setCenter(new TMap.LatLng(lat, lng));
  } catch (error) {
    console.error("地址解析失败:", error);
  }
}

// 清除所有标记
function clearMarkers() {
  // 清空标记数组
  markers = [];
  // 通过MultiMarker图层清除所有标记
  if (multiMarker) {
    multiMarker.setGeometries(markers);
  }
}

// 选择位置
const selectLocation = () => {
  // 当前位置
  formData.address.name = locationObj.value.address;
  formData.address.detail =
    locationObj.value.formatted_addresses.standard_address;
  formData.address.lat = locationObj.value.ad_info.location.lat;
  formData.address.lng = locationObj.value.ad_info.location.lng;

  initMap(locationObj.value.location.lat, locationObj.value.location.lng);

  Taro.showToast({
    title: "位置选择成功",
    icon: "success",
  });
};

// 提交表单
const submitForm = async () => {
  // 验证必填项
  if (!formData.title) {
    Taro.showToast({
      title: "请输入任务标题",
      icon: "none",
    });
    return;
  }

  if (!formData.startDate) {
    Taro.showToast({
      title: "请选择开始日期",
      icon: "none",
    });
    return;
  }

  if (!formData.startTime || !formData.endTime) {
    Taro.showToast({
      title: "请选择签到时间段",
      icon: "none",
    });
    return;
  }

  if (!formData.address.name) {
    Taro.showToast({
      title: "请选择签到位置",
      icon: "none",
    });
    return;
  }

  if (!formData.amount) {
    Taro.showToast({
      title: "请输入任务金额",
      icon: "none",
    });
    return;
  }

  const submitData = ref({
    id: taskId.value,
    title: formData.title,
    describe_str: formData.description,
    startdate: formData.startDate,
    enddate: formData.endDate,
    checktime: formData.startTime,
    deadline: formData.endTime,
    taskamount: formData.amount,
    longitude: formData.address.lng,
    latitude: formData.address.lat,
    check_range: formData.address.range,
    fulladdress: formData.address.detail,
    number: formData.number,
  });
  console.log("提交数据:", submitData.value);

  // API接口 - 更新签到任务
  const res = await post("/check/add", submitData.value);
  if (res.code == 0) {
    Taro.showToast({
      title: "签到任务更新成功！",
      icon: "success",
    });
    setTimeout(() => {
      Taro.navigateBack();
    }, 2000);
  }
};

// 页面加载时获取任务详情
onMounted(() => {
  const params = Taro.getCurrentInstance().router?.params;
  if (params) {
    taskId.value = params.id || '';
    taskType.value = params.type || '';
    
    if (taskId.value) {
      getTaskDetail();
    }
  }
});
</script>

<style lang="scss">
.pgs {
  .nut-cell-group__wrap {
    background: none !important;
    box-shadow: none !important;
  }

  .nut-input {
    border-radius: 16rpx;
    border: 1px solid #e5e7eb;
    transition: all 0.2s ease;

    &:focus {
      border-color: #3b82f6;
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
  }

  .nut-textarea {
    border-radius: 16rpx;
    border: 1px solid #e5e7eb;
    transition: all 0.2s ease;

    &:focus {
      border-color: #3b82f6;
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
  }

  .nut-button--primary {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    border: none;
    transition: all 0.2s ease;

    &:active {
      transform: translateY(1px);
      box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
    }
  }

  .nut-button--small {
    border-radius: 12rpx;
    font-weight: 500;
  }
}
</style>
